package top.codeora.aiollama.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于SearXNG 搜索，format->json  engine->百度
 */
@Slf4j
public class WebSearch2XngTool {

//    @Value("${search-api.Xng-api-key}")
//    private String apiKey;

    private static final String SEARCH_API_URL = "http://localhost:8080/search?";

    @Tool(description = "Search for information from Search Engine",name = "Search2Xng")
    public String searchWeb(@ToolParam(description = "Search query keyword") String query) {

        //构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("format", "json");
        paramMap.put("engine", "bing");
        log.info("请求参数：{}",paramMap.toString());

        String resultSearch = HttpUtil.get(SEARCH_API_URL, paramMap);
        if (StrUtil.isEmpty(resultSearch)) {
            log.warn("没有搜索到对应资料");
            return "搜索API返回错误: null";
        }

        // 解析返回结果
        JSONObject jsonResult = JSONUtil.parseObj(resultSearch);
        JSONArray jsonArray = jsonResult.getJSONArray("results");
        return formatSearchResults(jsonArray);
    }


    // 格式化搜索结果
    private String formatSearchResults(JSONArray results) {
        StringBuilder sb = new StringBuilder();

        int count = Math.min(results.size(), 5);
        for (int i = 0; i < count; i++) {
            JSONObject result = results.getJSONObject(i);

            sb.append(i + 1).append(". ");

            // 标题
            if (result.containsKey("title")) {
                sb.append(result.getStr("title")).append("\n");
            }

            // 链接
            if (result.containsKey("url")) {
                sb.append("链接: ").append(result.getStr("url")).append("\n");
            }

            // 摘要
            if (result.containsKey("content")) {
                sb.append(result.getStr("content")).append("\n");
            }

            // 日期（如果有）
            if (result.containsKey("publishedDate")) {
                sb.append("日期: ").append(result.getStr("publishedDate")).append("\n");
            }

            sb.append("\n");
        }
        log.info("SearchNGX搜索结果: {}", sb);
        return sb.toString();
    }

}
